<?php
  /***************************************************************
   * @file: loader.php
   * @author: Neo
   * @mail: xq262144@gmail.com
   * @date: 
   * @description:
   * this file is the loader of the framework
   ***************************************************************/
   
  if (!defined('SYS_BASEPATH')) {echo "No script access allowed!"; header("HTTP/1.0 404 Not Found"); } 
  
  class Loader
  {
    //using singleton model
    private static $loader_img = null;
    
    public static function get_instance() {
      return self::$loader_img != null ? self::$loader_img : (self::$loader_img  = new Loader());
    }
    
    //private construct method
    private function __construct() {
        
    }

	//loader of controller
	public function controller($controller_name) {
		if (file_exists(SYS_CONTROLLER . "/${controller_name}.php")) {
			require_once(SYS_CONTROLLER . "/${controller_name}.php");
			$controller_class = "${controller_name}_controller";
			return new $controller_class;
		}
		else{
			report_error("Controller ${controller_name} not found");
		}
	}
       
    //loader of view
    public function view($view_name) {
      if (file_exists(SYS_VIEW . "/${view_name}.php")) {
        if(defined('WAP'))
          return new WapView($view_name);
        else
          return new View($view_name);
      }
      else{
        report_error("View ${view_name} not found");
      }        
    }

    //loader of lang
    public function lang($lang_filename){
        if (defined('SYS_LANG')){
            $filename = SYS_LANG . "/${lang_filename}." . loadLang() . '.php';
            if (file_exists($filename)){
                include($filename);
                return $lang_map;
            }
            else{
                report_error("LangFile ${lang_filename} not found");
            }
        }
        else{
            report_error('Lang package not imported');
        }
    }
    
    //loader of model
    public function model($model_name) {
      if (file_exists(SYS_MODEL . "/${model_name}.php")) {
        require_once(SYS_MODEL . "/${model_name}.php");
        $model_name = str_replace('/', '_', $model_name);
        $model_class = "${model_name}_model";
        return new $model_class;
      }
      else{
        report_error("Model ${model_name} not found");
      }         
    }
    
    //loader of library
    public function library($library_name) {
      if (is_dir(SYS_LIB . "/${library_name}") && file_exists(SYS_LIB . "/${library_name}/main.php")) {
        require_once(SYS_LIB . "/${library_name}/main.php");  
      }
      else{
        report_error("Library ${library_name} not found");
      }
    }
    
    //loader of helper
    public function helper($helper_name) {
      if (file_exists(SYS_HELPER . "/${helper_name}.php")) {
        require_once(SYS_HELPER . "/${helper_name}.php");
      }
      else{
        report_error("Helper ${helper_name} not found");
      } 
    }
  }
?>
